<template>
    <div class="chat-container">
        <!-- 左侧会话列表 -->
        <aside class="chat-sidebar">
            <div class="sidebar-header">
                <span class="sidebar-title">AI Assistant</span>
                <el-button type="primary" icon="Plus" class="new-chat-btn" size="small" @click="createNewChat">
                    新建对话
                </el-button>
            </div>
            <div class="sidebar-content">
                <el-menu class="chat-menu" :default-active="String(selectedSessionId)" @select="handleSelectSession">
                    <el-menu-item v-for="session in sessions" :key="session.chatId" :index="String(session.chatId)">
                        {{ session.title }}
                    </el-menu-item>
                </el-menu>
                <div v-if="loading" class="loading-container">
                    <div class="loading-text">加载中...</div>
                </div>
                <div class="sidebar-group">
                    <div v-for="group in groups" :key="group.title" class="sidebar-group-item">
                        {{ group.title }}
                    </div>
                </div>
            </div>
        </aside>

        <!-- 右侧主内容区 -->
        <main class="chat-main">
            <!-- 顶部标题栏 -->
            <header class="chat-header">
                <span class="chat-title">对话：{{ currentSessionTitle }}</span>
            </header>

            <!-- 对话内容区 -->
            <section class="chat-content">
                <div class="messages-container" ref="messagesContainer">
                    <div v-for="item in currentMessages" :key="item.id" :class="['chat-bubble', item.role]">
                        <!-- AI助手消息，头像在左 -->
                        <template v-if="item.role === 'assistant'">
                            <img class="avatar left" :src="appConfig.aiAssistant.image"
                                :alt="appConfig.aiAssistant.alt" />
                            <div class="bubble-content assistant-bubble">
                                <MarkdownRenderer :content="item.content" />
                            </div>
                        </template>
                        <!-- 用户消息，头像在右 -->
                        <template v-else>
                            <div class="bubble-content user-bubble">
                                <MarkdownRenderer :content="item.content" />
                            </div>
                            <img class="avatar right" :src="appConfig.userAvatar.image"
                                :alt="appConfig.userAvatar.alt" />
                        </template>
                    </div>
                </div>

                <!-- 滚动到底部按钮 -->
                <div v-if="showScrollToBottom" class="scroll-to-bottom-btn" @click="scrollToBottom(true)">
                    <el-icon>
                        <ArrowDown />
                    </el-icon>
                </div>
            </section>

            <!-- 底部输入区 -->
            <footer class="chat-footer">
                <div class="input-container">
                    <el-input v-model="inputText" class="chat-input" placeholder="输入消息..." @keyup.enter="sendMessage"
                        :rows="1" type="textarea" resize="none" autosize />
                    <el-button type="primary" class="send-btn" @click="sendMessage"
                        :disabled="!inputText.trim() || sending">
                        {{ sending ? '发送中...' : '发送' }}
                    </el-button>
                </div>
            </footer>
        </main>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { Plus, ArrowDown } from '@element-plus/icons-vue'
import { appConfig } from '@/config/app'
import { generateChatId } from '@/utils/idGenerator'
import { getChatSessions, getChatDetail, sendMessage as sendMessageApi, sendMessageStream } from '@/api/chat'
import type { ChatSession, ChatDetail, ChatMessage } from '@/api/chat/models'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

// 定义消息类型
interface Message {
    id: number
    role: 'assistant' | 'user'
    content: string
}

// 定义会话类型
interface Session {
    chatId: string
    title: string
    messages: Message[]
}

// 加载状态
const loading = ref(false)
const sending = ref(false)

// 会话列表和分组模拟数据
const sessions = ref<Session[]>([])

// 初始化数据
const initData = async () => {
    loading.value = true
    try {
        // 获取会话列表
        const sessionsData = await getChatSessions('chat')
        // 转换API数据格式到本地格式
        sessions.value = sessionsData.map((session: ChatSession) => ({
            chatId: session.chatId,
            title: session.chatName,
            messages: []
        }))

        // 如果有会话，加载第一个会话的详情
        if (sessions.value.length > 0) {
            await loadChatDetail(sessions.value[0].chatId)
            selectedSessionId.value = sessions.value[0].chatId
        }
    } catch (error) {
        console.error('初始化数据失败:', error)
        // 使用模拟数据作为后备
        sessions.value = [
            {
                chatId: 'abc123',
                title: '如何使用API功能',
                messages: [
                    { id: 1, role: 'assistant', content: '你好！我是AI助手，有什么我可以帮您的吗？' },
                    { id: 2, role: 'user', content: '请问如何调用生成API？' },
                    { id: 3, role: 'assistant', content: '调用生成API需要以下步骤：\n1. 在控制台创建API密钥\n2. 通过HTTP POST请求发送数据\n3. 处理返回的JSON响应' },
                ]
            }
        ]
        selectedSessionId.value = 'abc123'
    } finally {
        loading.value = false
    }
}

// 加载会话详情
const loadChatDetail = async (chatId: string) => {
    try {
        const chatDetail = await getChatDetail(chatId)
        const session = sessions.value.find(s => s.chatId === chatId)
        if (session) {
            // 转换API消息格式到本地格式
            session.messages = chatDetail.messages.map((msg: ChatMessage, index: number) => ({
                id: index + 1,
                role: msg.sender,
                content: msg.content
            }))

            // 加载完成后确保滚动到底部
            nextTick(() => {
                scrollToBottom(false)
            })
        }
    } catch (error) {
        console.error('加载会话详情失败:', error)
    }
}

const groups = ref([
    { title: '最新AI技术讨论' },
    { title: '数据分析最佳实践' },
    { title: '机器学习入门课程' },
    { title: '前端开发技巧' },
    { title: '后端架构设计' },
])

const selectedSessionId = ref('abc123')
const inputText = ref('')
const messagesContainer = ref<HTMLElement | null>(null)
const showScrollToBottom = ref(false)

// 防抖函数
const debounce = (func: Function, wait: number) => {
    let timeout: number
    return function executedFunction(...args: any[]) {
        const later = () => {
            clearTimeout(timeout)
            func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
    }
}

// 当前会话的消息
const currentMessages = computed(() => {
    const session = sessions.value.find(s => s.chatId === selectedSessionId.value)
    return session ? session.messages : []
})

const currentSessionTitle = computed(() => {
    const session = sessions.value.find(s => s.chatId === selectedSessionId.value)
    return session ? session.title : ''
})

// 创建新对话
const createNewChat = () => {
    const newChatId = generateChatId()
    const newSession: Session = {
        chatId: newChatId,
        title: `新对话 ${newChatId}`,
        messages: [
            {
                id: Date.now(),
                role: 'assistant',
                content: '你好！我是AI助手，有什么我可以帮您的吗？'
            }
        ]
    }

    // 添加新会话到列表开头
    sessions.value.unshift(newSession)

    // 切换到新会话
    selectedSessionId.value = newChatId

    // 清空输入框
    inputText.value = ''

    // 创建新对话时立即滚动到底部
    scrollToBottom(false)
}

// 自动滚动到底部
const scrollToBottom = (smooth: boolean = true) => {
    nextTick(() => {
        if (messagesContainer.value) {
            const container = messagesContainer.value
            const scrollHeight = container.scrollHeight
            const clientHeight = container.clientHeight

            // 使用平滑滚动或立即滚动
            if (smooth) {
                container.scrollTo({
                    top: scrollHeight,
                    behavior: 'smooth'
                })
            } else {
                container.scrollTop = scrollHeight
            }

            // 确保滚动到底部（处理可能的精度问题）
            setTimeout(() => {
                if (container.scrollTop + clientHeight < scrollHeight - 10) {
                    container.scrollTop = scrollHeight
                }
            }, 100)
        }
    })
}

// 检查是否需要滚动到底部
const shouldScrollToBottom = () => {
    if (!messagesContainer.value) return false

    const container = messagesContainer.value
    const { scrollTop, scrollHeight, clientHeight } = container

    // 如果用户滚动位置接近底部（距离底部小于50px），则认为需要自动滚动
    return scrollTop + clientHeight >= scrollHeight - 50
}

// 智能滚动到底部（只在用户接近底部时自动滚动）
const smartScrollToBottom = () => {
    if (shouldScrollToBottom()) {
        scrollToBottom(true)
    }
}

async function sendMessage() {
    if (!inputText.value.trim() || sending.value) return

    const userContent = inputText.value.trim()
    inputText.value = ''
    sending.value = true

    const currentSession = sessions.value.find(s => s.chatId === selectedSessionId.value)
    if (!currentSession) return

    // 添加用户消息
    const userMessage: Message = {
        id: Date.now(),
        role: 'user',
        content: userContent
    }
    currentSession.messages.push(userMessage)
    // 用户发送消息时强制滚动到底部
    scrollToBottom(true)

    try {
        // 调用API发送消息
        const res = await sendMessageApi({
            chatId: selectedSessionId.value,
            content: userContent
        })
        console.log(res);

        // 添加AI回复
        const assistantMessage: Message = {
            id: Date.now() + 1,
            role: 'assistant',
            content: typeof res === 'string' ? res : '我已经收到您的消息，有什么可以帮助您的吗？'
        }
        currentSession.messages.push(assistantMessage)
    } catch (error) {
        console.error('发送消息失败:', error)
        // 添加错误消息
        const errorMessage: Message = {
            id: Date.now() + 1,
            role: 'assistant',
            content: '抱歉，网络连接出现问题，请检查网络后重试。'
        }
        currentSession.messages.push(errorMessage)
    } finally {
        sending.value = false
        // AI回复时也强制滚动到底部
        scrollToBottom(true)
    }
}

async function handleSelectSession(id: string) {
    selectedSessionId.value = id
    // 清空输入框
    inputText.value = ''

    // 加载会话详情
    await loadChatDetail(id)

    // 切换会话时强制滚动到底部（不使用平滑滚动，立即显示）
    scrollToBottom(false)
}

// 监听会话切换，确保切换到新会话时滚动到底部
watch(selectedSessionId, () => {
    nextTick(() => {
        scrollToBottom(false)
    })
})

// 监听滚动事件，控制滚动到底部按钮的显示
const handleScroll = debounce(() => {
    if (messagesContainer.value) {
        const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value
        // 如果距离底部超过100px，显示滚动到底部按钮
        showScrollToBottom.value = scrollTop + clientHeight < scrollHeight - 100
    }
}, 100)

// 在组件挂载后添加滚动监听器
onMounted(() => {
    initData()

    // 添加滚动事件监听器
    if (messagesContainer.value) {
        messagesContainer.value.addEventListener('scroll', handleScroll)
    }
})

// 监听当前消息变化，自动滚动到底部
watch(currentMessages, (newMessages, oldMessages) => {
    // 如果消息数量增加，说明有新消息，需要滚动到底部
    if (newMessages.length > (oldMessages?.length || 0)) {
        nextTick(() => {
            scrollToBottom(true)
        })
    }
}, { deep: true })
</script>

<style scoped>
/* 根容器 */
.chat-container {
    display: grid;
    grid-template-columns: 260px 1fr;
    grid-template-rows: 1fr;
    height: 100%;
    background: #f7f8fa;
    overflow: hidden;
}

/* 侧边栏 */
.chat-sidebar {
    display: flex;
    flex-direction: column;
    background: #fff;
    border-right: 1px solid #ececec;
    height: 100%;
    overflow: hidden;
}

.sidebar-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    border-bottom: 1px solid #ececec;
    height: 56px;
    box-sizing: border-box;
}

.sidebar-title {
    font-size: 18px;
    font-weight: bold;
    color: #222;
}

.new-chat-btn {
    margin-left: 8px;
}

.sidebar-content {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
    min-height: 0;
}

.chat-menu {
    flex: 1;
    border: none;
    background: transparent;
    overflow-y: auto;
    min-height: 0;
}

.sidebar-group {
    padding: 12px 24px;
    border-top: 1px solid #ececec;
    background: #fff;
}

.sidebar-group-item {
    color: #888;
    font-size: 14px;
    margin-bottom: 8px;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.sidebar-group-item:hover {
    background-color: #f5f5f5;
}

.loading-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    color: #999;
}

.loading-text {
    font-size: 14px;
}

/* 主内容区 */
.chat-main {
    display: flex;
    flex-direction: column;
    background: #f7f8fa;
    height: 100%;
    overflow: hidden;
}

.chat-header {
    display: flex;
    align-items: center;
    padding: 0 24px;
    background: #fff;
    border-bottom: 1px solid #ececec;
    height: 56px;
    box-sizing: border-box;
}

.chat-title {
    color: #222;
    font-size: 16px;
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 聊天内容区域 */
.chat-content {
    display: flex;
    flex-direction: column;
    flex: 1;
    background: #f7f8fa;
    padding: 16px 24px;
    overflow: hidden;
    min-height: 0;
    position: relative;
}

.messages-container {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0 8px 20px 0;
    scroll-behavior: smooth;
    will-change: scroll-position;
    min-height: 0;
}

/* 滚动到底部按钮 */
.scroll-to-bottom-btn {
    position: absolute;
    bottom: 20px;
    right: 20px;
    width: 40px;
    height: 40px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
    z-index: 10;
    color: white;
}

.scroll-to-bottom-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.scroll-to-bottom-btn .el-icon {
    font-size: 16px;
}

/* 消息气泡 */
.chat-bubble {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16px;
    padding: 0 4px;
}

.chat-bubble.assistant {
    flex-direction: row;
    justify-content: flex-start;
}

.chat-bubble.user {
    flex-direction: row;
    justify-content: flex-end;
}

.bubble-content {
    background: #fff;
    border-radius: 12px;
    padding: 12px 16px;
    font-size: 14px;
    color: #222;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    max-width: 65%;
    line-height: 1.5;
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: break-word;
}

/* AI助手消息 - 蓝色底色 */
.bubble-content.assistant-bubble {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    color: #222;
    border: 1px solid #90caf9;
}

.bubble-content.user-bubble {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    margin-right: 8px;
}

/* AI消息中的Markdown内容样式 */
.bubble-content.assistant-bubble :deep(.markdown-content) {
    color: var(--text-color);
}

.bubble-content.assistant-bubble :deep(.markdown-content code) {
    background-color: rgba(0, 0, 0, 0.1);
    color: var(--text-color);
}

.bubble-content.assistant-bubble :deep(.markdown-content pre) {
    background-color: rgba(0, 0, 0, 0.05);
}

.bubble-content.assistant-bubble :deep(.markdown-content pre code) {
    background-color: transparent;
    color: var(--text-color);
}

.bubble-content.assistant-bubble :deep(.markdown-content a) {
    color: #1976d2;
    text-decoration: underline;
}

.bubble-content.assistant-bubble :deep(.markdown-content blockquote) {
    border-left-color: #90caf9;
    color: #424242;
}

/* 用户消息中的Markdown内容样式 */
.bubble-content.user-bubble :deep(.markdown-content) {
    color: #fff;
}

.bubble-content.user-bubble :deep(.markdown-content code) {
    background-color: rgba(255, 255, 255, 0.2);
    color: #fff;
}

.bubble-content.user-bubble :deep(.markdown-content pre) {
    background-color: rgba(255, 255, 255, 0.1);
}

.bubble-content.user-bubble :deep(.markdown-content pre code) {
    background-color: transparent;
    color: #fff;
}

.bubble-content.user-bubble :deep(.markdown-content a) {
    color: #fff;
    text-decoration: underline;
}

.bubble-content.user-bubble :deep(.markdown-content blockquote) {
    border-left-color: rgba(255, 255, 255, 0.3);
    color: rgba(255, 255, 255, 0.9);
}

/* 头像 */
.avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    object-fit: cover;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    margin-top: 4px;
}

.avatar.left {
    margin-right: 8px;
}

.avatar.right {
    margin-left: 8px;
}

/* 底部输入区域 */
.chat-footer {
    background: #fff;
    border-top: 1px solid #ececec;
    padding: 16px 24px;
    display: flex;
    align-items: center;
    min-height: 80px;
    box-sizing: border-box;
}

.input-container {
    display: flex;
    align-items: flex-end;
    gap: 12px;
    width: 100%;
}

.chat-input {
    flex: 1;
    min-width: 0;
}

:deep(.chat-input .el-textarea__inner) {
    border-radius: 20px;
    border: 1px solid #e0e0e0;
    padding: 12px 20px;
    font-size: 14px;
    line-height: 1.5;
    resize: none;
    transition: all 0.2s ease;
    min-height: 40px;
    max-height: 120px;
}

:deep(.chat-input .el-textarea__inner:focus) {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.send-btn {
    min-width: 80px;
    height: 40px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    transition: all 0.2s ease;
}

.send-btn:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.send-btn:disabled {
    background: #f5f5f5;
    color: #999;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
    width: 6px;
}

.messages-container::-webkit-scrollbar-track {
    background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
    background: rgba(0, 0, 0, 0.3);
}

:deep(.chat-menu::-webkit-scrollbar) {
    width: 4px;
}

:deep(.chat-menu::-webkit-scrollbar-track) {
    background: transparent;
}

:deep(.chat-menu::-webkit-scrollbar-thumb) {
    background: #ddd;
    border-radius: 2px;
}

:deep(.chat-menu::-webkit-scrollbar-thumb:hover) {
    background: #ccc;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .chat-container {
        grid-template-columns: 240px 1fr;
    }
}

@media (max-width: 1024px) {
    .chat-container {
        grid-template-columns: 220px 1fr;
    }

    .chat-content,
    .chat-footer {
        padding: 12px 16px;
    }

    .chat-header {
        padding: 0 16px;
    }

    .sidebar-header {
        padding: 16px 16px;
    }

    .sidebar-group {
        padding: 12px 16px;
    }
}

@media (max-width: 768px) {
    .chat-container {
        grid-template-columns: 200px 1fr;
    }

    .bubble-content {
        max-width: 75%;
    }

    .sidebar-header {
        padding: 12px 12px;
    }

    .sidebar-title {
        font-size: 16px;
    }

    .chat-header {
        padding: 0 12px;
    }
}

@media (max-width: 480px) {
    .chat-container {
        grid-template-columns: 180px 1fr;
    }

    .bubble-content {
        max-width: 80%;
        font-size: 13px;
        padding: 10px 14px;
    }

    .avatar {
        width: 28px;
        height: 28px;
    }

    .chat-content,
    .chat-footer {
        padding: 8px 12px;
    }

    .sidebar-header {
        padding: 8px 8px;
    }

    .sidebar-group {
        padding: 8px 8px;
    }
}

@media (max-width: 360px) {
    .chat-container {
        grid-template-columns: 160px 1fr;
    }

    .sidebar-header {
        padding: 8px 6px;
    }

    .sidebar-title {
        font-size: 14px;
    }

    .chat-header {
        padding: 0 6px;
    }

    .chat-title {
        font-size: 14px;
    }

    .sidebar-group {
        padding: 6px 6px;
    }
}
</style>